import {Component, OnInit} from '@angular/core';
import {environment} from "../../../../../environments/environment";
import {StringTool} from "../../../../tools";
import {NzUploadChangeParam} from "ng-zorro-antd/upload";
import {UploadFileInfo} from "./upload-file-info";
import {ResponseEntity} from "../../../../services/http/response-entity";
import {NzMessageService} from "ng-zorro-antd/message";
import {ImageService} from "../image.service";

@Component({
  selector: 'app-pic-upload',
  templateUrl: './pic-upload.component.html',
  styleUrls: ['./pic-upload.component.less']
})
export class PicUploadComponent implements OnInit {
  static UPLOAD_ADDR = StringTool.concatUrl(environment.service.servicePrefix, environment.serverName.document, "document-upload/image")
  static DOWNLOAD_URL = StringTool.concatUrl(environment.service.servicePrefix, environment.serverName.document, "document-download/image")

  uploadAddr = PicUploadComponent.UPLOAD_ADDR
  private downloadUrl = PicUploadComponent.DOWNLOAD_URL
  srcArray: UploadFileInfo[] = []
  srcTmp: string

  constructor(private msg: NzMessageService, private imageService: ImageService) {
  }

  ngOnInit(): void {
  }

  confirm(src: string) {
    const info = new UploadFileInfo();
    info.type = 'out';
    info.url = src
    this.srcArray.push(info);
    this.srcTmp = null
  }

  handleChange(e: NzUploadChangeParam) {
    if (e.type !== 'success') {
      return
    }
    const file = e.file;
    const fileName = file.name;
    const response = file.response as ResponseEntity<any>;
    if (response.status === '0') {
      const data = response.data;
      const id = data[fileName];
      const info = new UploadFileInfo();
      info.url = StringTool.concatUrl(this.downloadUrl, id);
      info.type = 'inner';
      info.id = id
      info.fileName = fileName
      this.srcArray.push(info);
      this.msg.success("上传成功！")
    } else {
      this.msg.error(`上传出错,文件：${fileName},Message:${response.message}`, {nzDuration: 10000})
    }
  }

  remove(index) {
    const infoList = this.srcArray.splice(index, 1)
    if (infoList != null && infoList.length) {
      for (let i = 0; i < infoList.length; i++) {
        const info = infoList[i];
        if (info.type === 'inner' && info.id) {
          this.imageService.deleteById(info.id).subscribe(value => console.log(value))
        }
      }
    }
  }

}
